package io.renren.modules.mvs.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.Constant;
import io.renren.common.utils.MvsUtils;
import io.renren.common.utils.PageUtils;
import io.renren.modules.mvs.dao.MvsPaymentDao;
import io.renren.modules.mvs.dao.MvsPaymentDetailDao;
import io.renren.modules.mvs.dto.PaymentDetailDto;
import io.renren.modules.mvs.dto.PaymentDto;
import io.renren.modules.mvs.entity.PaymentDetailEntity;
import io.renren.modules.mvs.entity.PaymentEntity;
import io.renren.modules.mvs.service.PaymentService;
import io.renren.modules.sys.dao.SysRoleDao;
import io.renren.modules.sys.entity.SysRoleEntity;
import io.renren.modules.sys.entity.SysUserEntity;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

import static io.renren.common.utils.Constant.VEHICLE_OWNER;


@Service
public class PaymentServiceImpl extends ServiceImpl<MvsPaymentDao, PaymentEntity> implements PaymentService {
    @Autowired
    private SysRoleDao sysRoleDao;
    @Autowired
    private MvsPaymentDetailDao mvsPaymentDetailDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        long currPage = 1;
        long limit = 10;

        if (params.get(Constant.PAGE) != null) {
            currPage = Long.parseLong((String) params.get(Constant.PAGE));
        }
        if (params.get(Constant.LIMIT) != null) {
            limit = Long.parseLong((String) params.get(Constant.LIMIT));
        }

        SysUserEntity user = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
        Long userId = user.getUserId();
        List<SysRoleEntity> roles = sysRoleDao.queryListByUserId(userId);

        IPage<PaymentDto> page;
        // 如果角色是机动车车主，则只能看到缴纳人是自己的缴纳记录数据
        if (roles.size() == 1 && VEHICLE_OWNER.equals(roles.get(0).getRoleName())) {
            params.put("userId", userId);
        }
        page = this.baseMapper.selectPageByCondition(new Page<>(currPage, limit), params);

        // 查询出每个缴费记录的详细信息
        List<Long> paymentIds = page.getRecords().stream().map(PaymentDto::getId).collect(Collectors.toList());
        List<PaymentDetailDto> paymentDetails = mvsPaymentDetailDao.selectListByPaymentIds(paymentIds);
        // 根据paymentId分组
        Map<Long, List<PaymentDetailDto>> detailMap = paymentDetails
                .stream().collect(Collectors.groupingBy(PaymentDetailDto::getPaymentId));
        page.getRecords().forEach(item -> {
            List<PaymentDetailDto> temp = detailMap.get(item.getId());
            if (temp != null) {
                temp.sort(Comparator.comparing(PaymentDetailDto::getCreateTime).reversed());
                item.setDetailList(temp);
            }
        });

        return new PageUtils(page);
    }

    @Override
    public Map<String, Collection<?>> getMoneyListByDateRange(String startDate, String endDate) {
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
            // 如果startDate或endDate为空，去过去最近一周作为时间范围
            LocalDate end = LocalDate.now();
            LocalDate start = end.minusDays(6);
            startDate = start.toString();
            endDate = end.toString();
        }
        LocalDate start = LocalDate.parse(startDate);
        LocalDate end = LocalDate.parse(endDate);
        MvsUtils.checkDate(start, end);

        SysUserEntity user = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
        List<SysRoleEntity> roles = sysRoleDao.queryListByUserId(user.getUserId());
        // 如果角色是机动车车主，则只能看到自己的罚单数据
        if (roles.size() == 1 && VEHICLE_OWNER.equals(roles.get(0).getRoleName())) {
            List<Map<String, ?>> dbDataList = this.baseMapper.selectMoneyByDateRange(startDate, endDate, user.getUserId());
            return MvsUtils.getStatisticByDateRange(start, end, dbDataList);
        }
        List<Map<String, ?>> dbDataList = this.baseMapper.selectMoneyByDateRange(startDate, endDate, null);
        return MvsUtils.getStatisticByDateRange(start, end, dbDataList);
    }

    @Override
    public List<PaymentDetailDto> getDetailList(Long id) {
        return mvsPaymentDetailDao.selectListByPaymentIds(Collections.singletonList(id));
    }

}